document.addEventListener('DOMContentLoaded', () => {
    // 初始购物清单数据
    let shoppingList = JSON.parse(localStorage.getItem('shoppingList')) || [
        { id: 1, name: '牛奶', member: 'm1', purchased: false },
        { id: 2, name: '面包', member: 'm2', purchased: true },
        { id: 3, name: '鸡蛋', member: 'm3', purchased: false },
        { id: 4, name: '水果', member: 'm4', purchased: false },
        { id: 5, name: '蔬菜', member: 'm1', purchased: true }
    ];

    // DOM元素
    const itemsList = document.getElementById('itemsList');
    const newItemInput = document.getElementById('newItem');
    const addButton = document.getElementById('addButton');
    const memberSelect = document.getElementById('memberSelect');
    const memberTags = document.querySelectorAll('.member-tag');
    const searchInput = document.getElementById('searchInput');
    const totalItemsSpan = document.getElementById('totalItems');
    const pendingItemsSpan = document.getElementById('pendingItems');
    const purchasedItemsSpan = document.getElementById('purchasedItems');

    // 渲染购物清单
    function renderShoppingList(member = 'all', searchTerm = '') {
        itemsList.innerHTML = '';

        // 过滤条件
        let filteredList = shoppingList.filter(item => {
            const memberMatch = member === 'all' || item.member === member;
            const searchMatch = item.name.toLowerCase().includes(searchTerm.toLowerCase());
            return memberMatch && searchMatch;
        });

        // 排序：未完成的在前，按添加时间倒序
        filteredList.sort((a, b) => {
            if (a.purchased !== b.purchased) {
                return a.purchased ? 1 : -1;
            }
            return b.id - a.id;
        });

        // 如果没有物品显示空状态
        if (filteredList.length === 0) {
            itemsList.innerHTML = `
                <div class="empty-state">
                    <img src="data:image/svg+xml;base64,..." alt="空列表">
                    <h3>没有找到匹配的物品</h3>
                    <p>尝试调整搜索条件或添加新物品</p>
                </div>
            `;
            updateStats();
            return;
        }

        // 批量生成DOM元素（性能优化）
        const fragment = document.createDocumentFragment();

        filteredList.forEach(item => {
            const itemElement = createItemElement(item);
            fragment.appendChild(itemElement);
        });

        itemsList.appendChild(fragment);
        updateStats();
        addEventListeners();
    }

    // 创建单个物品元素
    function createItemElement(item) {
        const element = document.createElement('div');
        element.className = `item ${item.purchased ? 'purchased' : ''}`;
        element.dataset.id = item.id;

                // 获取成员颜色
        const memberColor = getComputedStyle(document.querySelector(`.member-tag[data-member="${item.member}"]`)).getPropertyValue('--member-color');

        element.innerHTML = `
            <div class="item-name">${escapeHtml(item.name)}</div>
            <div>
                <span class="member-badge" style="--member-color: ${memberColor || '#4361ee'}">
                    ${getMemberName(item.member)}
                </span>
            </div>
            <div class="status ${item.purchased ? 'purchased' : 'pending'}" data-id="${item.id}">
                <i class="fas ${item.purchased ? 'fa-check-circle' : 'fa-clock'}"></i>
                ${item.purchased ? '已完成' : '待购买'}
            </div>
            <div>
                <button class="delete-btn" data-id="${item.id}">
                    <i class="fas fa-trash-alt"></i> 删除
                </button>
            </div>
        `;

        return element;
    }

    // HTML特殊字符转义（安全防护）
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // 获取成员名称
    function getMemberName(memberId) {
        const memberNames = {
            'm1': '张三',
            'm2': '李四',
            'm3': '王五',
            'm4': '赵六'
        };
        return memberNames[memberId] || memberId;
    }

    // 更新统计信息
    function updateStats() {
        totalItemsSpan.textContent = shoppingList.length;
        pendingItemsSpan.textContent = shoppingList.filter(item => !item.purchased).length;
        purchasedItemsSpan.textContent = shoppingList.filter(item => item.purchased).length;
    }

    // 切换购买状态
    function togglePurchaseStatus(e) {
        const itemId = parseInt(e.currentTarget.dataset.id);
        const itemIndex = shoppingList.findIndex(item => item.id === itemId);

        if (itemIndex !== -1) {
            shoppingList[itemIndex].purchased = !shoppingList[itemIndex].purchased;
            saveToLocalStorage();
            renderShoppingList(
                document.querySelector('.member-tag.active').dataset.member,
                searchInput.value.trim()
            );

            // 添加动画反馈
            e.currentTarget.classList.add('pulse');
            setTimeout(() => {
                e.currentTarget.classList.remove('pulse');
            }, 300);
        }
    }

    // 删除物品
    function deleteItem(e) {
        if (confirm('确定要删除这个物品吗？')) {
            const itemId = parseInt(e.currentTarget.dataset.id);
            shoppingList = shoppingList.filter(item => item.id !== itemId);
            saveToLocalStorage();
            renderShoppingList(
                document.querySelector('.member-tag.active').dataset.member,
                searchInput.value.trim()
            );
        }
    }

    // 添加新物品
    function addNewItem() {
        const itemName = newItemInput.value.trim();
        if (itemName) {
            const newItem = {
                id: Date.now(), // 使用时间戳作为唯一ID
                name: itemName,
                member: memberSelect.value,
                purchased: false
            };

            shoppingList.unshift(newItem); // 新物品添加到开头
            saveToLocalStorage();
            renderShoppingList(
                document.querySelector('.member-tag.active').dataset.member,
                searchInput.value.trim()
            );

            // 清空输入框并显示添加动画
            newItemInput.value = '';
            addButton.innerHTML = '<i class="fas fa-check"></i> 已添加';
            addButton.style.backgroundColor = '#2ecc71';

            setTimeout(() => {
                addButton.innerHTML = '<i class="fas fa-plus"></i> 添加';
                addButton.style.backgroundColor = '';
            }, 1500);
        }
    }

    // 保存到LocalStorage
    function saveToLocalStorage() {
        localStorage.setItem('shoppingList', JSON.stringify(shoppingList));
    }

    // 添加事件监听器
    function addEventListeners() {
        document.querySelectorAll('.status').forEach(status => {
            status.addEventListener('click', togglePurchaseStatus);
        });

        document.querySelectorAll('.delete-btn').forEach(btn => {
            btn.addEventListener('click', deleteItem);
        });
    }

    // 初始化事件监听
    addButton.addEventListener('click', addNewItem);

    // 按Enter添加物品
    newItemInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            addNewItem();
        }
    });

    // 团队成员筛选
    memberTags.forEach(tag => {
        tag.addEventListener('click', () => {
            memberTags.forEach(t => t.classList.remove('active'));
            tag.classList.add('active');
            renderShoppingList(tag.dataset.member, searchInput.value.trim());
        });
    });

    // 搜索功能
    searchInput.addEventListener('input', debounce(() => {
        renderShoppingList(
            document.querySelector('.member-tag.active').dataset.member,
            searchInput.value.trim()
        );
    }, 300));

    // 防抖函数（优化搜索性能）
    function debounce(func, delay) {
        let timeoutId;
        return function() {
            clearTimeout(timeoutId);
            timeoutId = setTimeout(() => func.apply(this, arguments), delay);
        };
    }

    // 初始渲染
    renderShoppingList('all');
});
